// pages/compony-pages/issue-job/issue-job.js
const app = getApp();
import Toast from '../../../component/toast/toast';
const salaryArr = ['1K', '2K', '3K', '4K', '5K', '6K', '7K', '8K', '9K', '10K', '11K', '12K', '13K', '14K', '15K', '16K', '17K', '18K', '19K', '20K', '21K', '22K', '23K', '24K', '25K', '26K', '27K', '28K', '29K', '30K', '31k', '32K', '33K', '34K', '35K', '36K', '37K', '38K', '39K', '40K', '41K', '42K', '43K', '44K', '45K', '46K', '47K', '48K', '49K', '50K', '51K', '52K', '53K', '54K', '55K', '56K', '57K','58K','59K','60K','70K','80K','90K','100K','110K','120K','130K','140K','150K','160K','170K','180K','190K','200K','210K','220K','230K','240K','250K'];
import utils from '../../../utils/util.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        jobId:'',
        componyName: '',
        jobName: '',
        jobDesc: '',
        jobType: '',
        enterpriseInfo: '',
        jobWayObj: null,
        otherParams: {},
        education: null,
        experience: null,
        mode: null,
        skillType: null,
        skillNameArr: null,
        skills:[],
        salaryArray: [
            salaryArr,
            ['2K']
        ],
        salaryIndex:[0 , 0],
        selectSalary:null,
        workHour:null,
        flag:'',
        positionSkillId:''
    },
    /**
     * ===================事件处理部分===================
     */
    clickSkill(){
        if (!this.data.jobWayObj){
            Toast("请先选择职位类型！")
            return;
        }
        wx.navigateTo({
            url: '/pages/compony-pages/compony-select-skill/compony-select-skill?id='+this.data.jobWayObj.Id
        });
    },
    toAgreement() {
        app.globalData.globalWebUrl = app.globalData.agreementUrl.issueJobUrl;
        wx.navigateTo({
            url: '/pages/agreement-web/agreement-web?title=闲将信息发布规范'
        })
    },
    clickIssue(){
        if (!this.data.jobName){
            Toast("请填写职位名称！")
            return;
        }
        if (!this.data.jobType) {
            Toast("请选择职位类型！")
            return;
        }
        if (!this.data.skills) {
            Toast("请选择技能要求！")
            return;
        }
        if (!this.data.mode) {
            Toast("请选择工作方式！")
            return;
        }
        if (!this.data.selectSalary) {
            Toast("请选择薪资范围！")
            return;
        }
        if (!this.data.experience) {
            Toast("请选择经验要求！")
            return;
        }
        if (!this.data.education) {
            Toast("请选择学历要求！")
            return;
        }
        if (!this.data.jobDesc) {
            Toast("请选择职位描述！")
            return;
        }
        let data = this.joinEnterpriseData();
        this.addEnterprise(data);
    },
    clickRemove(){
        let that = this;
        wx.showModal({
            title: '温馨提示',
            content: '您确定要删除当前职位吗？',
            showCancel: true,
            cancelText: '取消',
            cancelColor: '#4EB262',
            confirmText: '确定',
            confirmColor: '#222',
            success: function (res) {
                if (res.confirm) {
                    that.deleteEnterpriseJob();
                }
            }
        })
    },  
    bindSalaryItemPickerChange(e){
        // console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
        let data = {
            salaryArray: this.data.salaryArray,
            salaryIndex: this.data.salaryIndex
        }
        if(e.detail.column == 0){
            let arr = this.getNextSalaryData(e.detail.value);
            data.salaryArray[1] = arr;
            data.salaryIndex[0] = e.detail.value;
            this.setData(data);
        }
        else if(e.detail.column == 1){
            data.salaryIndex[1] = e.detail.value;
        }
        
    },
    bindSalaryPickerChange(e){
        let data = {
            selectSalary:[],
            salaryIndex: this.data.salaryIndex
        };
        data.selectSalary.push(this.data.salaryArray[0][data.salaryIndex[0]]);
        data.selectSalary.push(this.data.salaryArray[1][data.salaryIndex[1]]);
        this.setData(data);
    },
    /**
     * 技能要求选择，多选去重
     */
    skillPickerChange(e) {
        let that = this;
        if (that.data.skillNameArr && that.data.skillNameArr.length >= 3){
            Toast("最多只能选择3个标签哦~");
            return;
        }
        let data = {
            skillNameArr: that.data.skillNameArr,
            skills: that.data.skills
        };
        let skillObj = {
            JobInfoId: '',
            SkillName: '',
            SortNo: 0
        }
        let skillName = that.data.skillType[e.detail.value].SkillName;
        skillObj.JobInfoId = that.data.skillType[e.detail.value].PositionId;
        skillObj.SkillName = skillName;
        skillObj.SortNo = that.data.skillType[e.detail.value].SortNo;
        if (data.skillNameArr){
            for(let i = 0 ; i < data.skillNameArr.length; i++){
                if (data.skillNameArr[i] == skillName){
                    return;
                }
            }
            data.skillNameArr.push(skillName);
            data.skills.push(skillObj);
        }else{
            data.skillNameArr = [];
            data.skillNameArr.push(skillName);
            data.skills.push(skillObj);
        }
        this.setData(data);
    },
    educationPickerChange(e) {
        let that = this;
        this.setData({
            education: that.data.otherParams.EducationData[e.detail.value]
        })
    },
    experiencePickerChange(e) {
        let that = this;
        this.setData({
            experience: that.data.otherParams.ExperienceData[e.detail.value]
        })
    },
    modePickerChange(e) {
        let that = this;
        this.setData({
            mode: that.data.otherParams.ModeData[e.detail.value]
        });
    },
    workHoursPickerChange(e) {
        let that = this;
        this.setData({
            workHour: that.data.otherParams.WorkingHoursData[e.detail.value]
        });
    },
    onClick(e) {
        let index = e.currentTarget.dataset.index;
        let url = '';
        switch (index) {
            case '1':
                if (this.data.flag == '1'){
                    return;
                }
                url = '/pages/compony-pages/issue-write/issue-write?jobName=' + this.data.jobName;
                break;
            case '2':
                url = '/pages/compony-pages/job-description/job-description?jobDesc=' + this.data.jobDesc;
                break;
        }
        wx.navigateTo({
            url: url
        })
    },
    jobWay() {
        wx.navigateTo({
            url: '/pages/compony-pages/job-way/job-way'
        })
    },
    /**
     * 薪资范围筛选
     */
    getNextSalaryData(index){
        let arr = [];
        let startIndex = index + 1;
        let size = startIndex + startIndex;
        if(size >= 10){
            size = startIndex + 10;
        }
        if(index >= 49){
            size = 60;
        }
        if(index >= 59){
            size = startIndex + 5;
        }
        if (index >= salaryArr.length - 6){
            size = salaryArr.length;
            arr = [];
        }
        if(index >= salaryArr.length - 1){
            arr.push(salaryArr[salaryArr.length-1]);
        }
        for(;startIndex < size; startIndex++){
            arr.push(salaryArr[startIndex]);
        }
        return arr;
    },
    /**
     * ===================事件处理部分===================
     */
    /**
     * -------------------网络请求部分-------------------
     */
    joinEnterpriseData(){
        let obj = {};
        obj.Id = this.data.jobId;
        obj.EnterpriseInfoId = app.globalData.enterpriseInfo.Id;
        obj.JobName = this.data.jobName;
        obj.JobPosition = this.data.jobWayObj.Id;
        obj.JobMode = this.data.mode.Id;
        obj.SalaryMin = this.data.selectSalary[0].split('K')[0];
        obj.SalaryMax = this.data.selectSalary[1].split('K')[0];
        obj.Experience = this.data.experience.Id;
        obj.Education = this.data.education.Id;
        obj.JobDes = this.data.jobDesc;
        obj.JobStatus = 0;
        obj.CreateDateTime = utils.formatTime(new Date());
        obj.Skills = this.data.skills;
        console.log(JSON.stringify(obj));
        return obj;
    },
    addEnterprise(data){
        let that = this;
        wx.showLoading({
            title: '正在发布职位...',
            mask: true
        });
        let url = '';
        if (this.data.flag == '1') {
            url = app.globalData.serverAddress.editEnterpriseJob
        }else{
            url = app.globalData.serverAddress.addEnterprise
        }
        console.log(url);
        wx.request({
            url: url,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            data:data,
            method: 'POST',
            success: function (res) {
                console.log("addEnterprise success：", res.data);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    Toast(res.data.Message);
                    setTimeout(function(){
                        wx.navigateBack({
                            delta: 5,
                        });
                    } , 800)
                }else{
                    Toast(res.data.Message);
                }
            },
            fail: function (res) {
                console.log("addEnterprise fail", res)
            },
            complete: function (res) {
                wx.hideLoading()
            },
        });
    },
    getPositionOtherParams() {
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        wx.request({
            url: app.globalData.serverAddress.getPositionOtherParams,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            method: 'GET',
            success: function(res) {
                console.log("getPositionOtherParams success：", res.data.BodyContent);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    that.setData({
                        otherParams: res.data.BodyContent
                    });
                }
            },
            fail: function(res) {
                console.log("getPositionOtherParams fail", res)
            },
            complete: function(res) {
                wx.hideLoading()
            },
        });
    },
    getPositionSkillData(id) {
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        wx.request({
            url: app.globalData.serverAddress.getPositionSkillData,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            data: {
                positionId: id
            },
            method: 'GET',
            success: function(res) {
                console.log("getPositionSkillData success：", res.data.BodyContent);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    that.setData({
                        skillType: res.data.BodyContent
                    });
                }
            },
            fail: function(res) {
                console.log("getPositionSkillData fail", res)
            },
            complete: function(res) {
                wx.hideLoading()
            },
        })
    },
    deleteEnterpriseJob(){
        let that = this;
        wx.showLoading({
            title: '加载中...',
            mask: true
        })
        wx.request({
            url: app.globalData.serverAddress.deleteEnterpriseJob,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            data: {
                JobInfoId: that.data.jobId,
                CurrentUserInfoId: app.userInfo.Id
            },
            method: 'POST',
            success: function (res) {
                console.log("deleteEnterpriseJob success：", res.data.BodyContent);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    Toast(res.data.Message);
                    setTimeout(function () {
                        wx.navigateBack({
                            delta: 5,
                        });
                    }, 800)
                }else{
                    Toast(res.data.Message);
                }
            },
            fail: function (res) {
                console.log("deleteEnterpriseJob fail", res)
            },
            complete: function (res) {
                wx.hideLoading()
            },
        })
    },
    /**
     * -------------------网络请求部分-------------------
     */
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.setData({
            // enterpriseInfo: app.globalData.enterpriseInfo,
            componyName: app.globalData.enterpriseInfo.EnterpriseName
        });
        this.getPositionOtherParams();
        if (options.flag){
            //编辑职位
            this.setData({
                flag: options.flag
            })
            this.setEditJobInfo();
        }
    },
    setEditJobInfo(){
        console.log(app.globalData.editJobInfo);
        let editJobInfo = app.globalData.editJobInfo;
        let data = {
            jobName: editJobInfo.JobName,
            jobType: editJobInfo.JobPositionText,
            skills: editJobInfo.Skills,
            mode:{},
            workHour:{},
            selectSalary:[],
            experience:{},
            education:{},
            jobWayObj:{}
        };
        data.skillNameArr = [];
        for (let i = 0; i < editJobInfo.Skills.length;i++){
            data.skillNameArr.push(editJobInfo.Skills[i].SkillName);
        }
        data.mode.ParamName = editJobInfo.JobModeText;
        data.mode.Id = editJobInfo.JobMode;
        data.workHour.ParamName = editJobInfo.WorkingHoursText;
        data.workHour.Id = editJobInfo.WorkingHours;
        data.selectSalary = editJobInfo.SalaryRange.split('-');
        data.experience.ParamName = editJobInfo.ExperienceText;
        data.experience.Id = editJobInfo.Experience;
        data.education.Id = editJobInfo.Education;
        data.education.ParamName = editJobInfo.EducationText;
        data.jobDesc = editJobInfo.JobDes;
        data.jobWayObj.Id = editJobInfo.JobPosition;
        data.jobId = editJobInfo.Id;
        this.setData(data);
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})